#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
题目管理API路由
"""

from flask import Blueprint, request, jsonify
from utils import format_response
from decorators import login_required, teacher_required, admin_required, get_current_user
from models import Problem, db
from services.problem_generator import ProblemGenerator
import json

problems_bp = Blueprint('problems', __name__)

# 初始化题目生成器
problem_generator = ProblemGenerator()

@problems_bp.route('/', methods=['GET'])
@login_required
def get_problems():
    """获取题目列表"""
    try:
        current_user = get_current_user()
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        difficulty = request.args.get('difficulty')
        language = request.args.get('language')
        search = request.args.get('search')
        
        query = Problem.query
        
        # 过滤条件
        if difficulty:
            query = query.filter(Problem.difficulty == difficulty)
        if language:
            query = query.filter(Problem.language == language)
        if search:
            query = query.filter(Problem.title.contains(search) | Problem.description.contains(search))
        
        # 分页
        problems = query.paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        problem_list = []
        for problem in problems.items:
            problem_dict = problem.to_dict()
            # 学生不显示答案，但对于代码补全题目需要显示模板
            if current_user.role == 'student' and problem.type != 'code_completion':
                problem_dict.pop('answer', None)
            problem_list.append(problem_dict)
        
        return jsonify(format_response({
            'problems': problem_list,
            'total': problems.total,
            'pages': problems.pages,
            'current_page': page,
            'per_page': per_page
        }))
        
    except Exception as e:
        return jsonify(format_response(message=str(e), code=500)), 500

@problems_bp.route('/<int:problem_id>', methods=['GET'])
@login_required
def get_problem(problem_id):
    """获取单个题目详情"""
    try:
        current_user = get_current_user()
        problem = Problem.query.get_or_404(problem_id)
        
        problem_dict = problem.to_dict()
        # 学生不显示答案，但对于某些题型需要保留答案用于前端验证
        # code_completion: 需要代码模板
        # choice: 需要答案验证选择结果  
        # blank: 需要答案验证填空内容
        # short: 需要答案进行关键词匹配评分
        if current_user.role == 'student' and problem.type not in ['code_completion', 'choice', 'blank', 'short']:
            problem_dict.pop('answer', None)
        
        return jsonify(format_response(problem_dict))
        
    except Exception as e:
        return jsonify(format_response(message=str(e), code=500)), 500

@problems_bp.route('/', methods=['POST'])
@teacher_required
def create_problem():
    """创建题目"""
    try:
        current_user = get_current_user()
        data = request.get_json()
        
        print(f"创建题目请求数据: {data}")
        print(f"当前用户: {current_user}")
        
        # 验证必需字段
        required_fields = ['title', 'description', 'type', 'difficulty']
        for field in required_fields:
            if not data.get(field):
                print(f"缺少必需字段: {field}")
                return jsonify(format_response(message=f"{field}不能为空", code=400)), 400
        
        # 处理测试用例和选项数据
        test_cases_data = data.get('test_cases')
        if test_cases_data and isinstance(test_cases_data, list):
            test_cases_json = json.dumps(test_cases_data)
        elif test_cases_data and isinstance(test_cases_data, str):
            test_cases_json = test_cases_data
        else:
            test_cases_json = None
            
        options_data = data.get('options')
        if options_data and isinstance(options_data, list):
            options_json = json.dumps(options_data)
        elif options_data and isinstance(options_data, str):
            options_json = options_data
        else:
            options_json = None
        
        # 创建新题目
        new_problem = Problem(
            title=data['title'],
            description=data['description'],
            type=data['type'],
            difficulty=data['difficulty'],
            language=data.get('language', 'python'),
            test_cases=test_cases_json,
            options=options_json,
            input_format=data.get('input_format'),
            output_format=data.get('output_format'),
            answer=data.get('answer'),
            points=data.get('points', 10),
            time_limit=data.get('time_limit', 1000),
            memory_limit=data.get('memory_limit', 64),
            created_by=current_user.id
        )
        
        print(f"准备保存题目: {new_problem.to_dict()}")
        
        db.session.add(new_problem)
        db.session.commit()
        
        result = new_problem.to_dict()
        print(f"题目创建成功: {result}")
        
        return jsonify(format_response(result, "题目创建成功"))
        
    except Exception as e:
        import traceback
        print(f"创建题目异常: {str(e)}")
        print(f"异常详情: {traceback.format_exc()}")
        db.session.rollback()
        return jsonify(format_response(message=str(e), code=500)), 500

@problems_bp.route('/<int:problem_id>', methods=['PUT'])
@teacher_required
def update_problem(problem_id):
    """更新题目"""
    try:
        problem = Problem.query.get_or_404(problem_id)
        data = request.get_json()
        
        # 更新字段
        if 'title' in data:
            problem.title = data['title']
        if 'description' in data:
            problem.description = data['description']
        if 'type' in data:
            problem.type = data['type']
        if 'difficulty' in data:
            problem.difficulty = data['difficulty']
        if 'language' in data:
            problem.language = data['language']
        if 'test_cases' in data:
            problem.test_cases = json.dumps(data['test_cases']) if data['test_cases'] else None
        if 'options' in data:
            problem.options = json.dumps(data['options']) if data['options'] else None
        if 'input_format' in data:
            problem.input_format = data['input_format']
        if 'output_format' in data:
            problem.output_format = data['output_format']
        if 'answer' in data:
            problem.answer = data['answer']
        if 'points' in data:
            problem.points = data['points']
        if 'time_limit' in data:
            problem.time_limit = data['time_limit']
        if 'memory_limit' in data:
            problem.memory_limit = data['memory_limit']
        
        db.session.commit()
        
        return jsonify(format_response(problem.to_dict(), "题目更新成功"))
        
    except Exception as e:
        db.session.rollback()
        return jsonify(format_response(message=str(e), code=500)), 500

@problems_bp.route('/<int:problem_id>', methods=['DELETE'])
@teacher_required
def delete_problem(problem_id):
    """删除题目"""
    try:
        problem = Problem.query.get_or_404(problem_id)
        db.session.delete(problem)
        db.session.commit()
        
        return jsonify(format_response(message="题目删除成功"))
        
    except Exception as e:
        db.session.rollback()
        return jsonify(format_response(message=str(e), code=500)), 500

# AI智能生成题目相关API
@problems_bp.route('/generate', methods=['POST'])
@teacher_required
def generate_problem():
    """AI生成题目"""
    try:
        data = request.get_json()
        
        topic = data.get('topic')
        difficulty = data.get('difficulty', 'medium')
        language = data.get('language', 'python')
        
        if not topic:
            return jsonify(format_response(message="主题不能为空", code=400)), 400
        
        result = problem_generator.generate_problem(topic, difficulty, language)
        
        if result['success']:
            return jsonify(format_response(result, "题目生成成功"))
        else:
            return jsonify(format_response(message=result['error'], code=500)), 500
            
    except Exception as e:
        return jsonify(format_response(message=str(e), code=500)), 500

@problems_bp.route('/generate-test-cases', methods=['POST'])
@teacher_required
def generate_test_cases():
    """AI生成测试用例"""
    try:
        data = request.get_json()
        
        problem_description = data.get('problem_description')
        language = data.get('language', 'python')
        
        if not problem_description:
            return jsonify(format_response(message="题目描述不能为空", code=400)), 400
        
        result = problem_generator.generate_test_cases(problem_description, language)
        
        if result['success']:
            return jsonify(format_response(result, "测试用例生成成功"))
        else:
            return jsonify(format_response(message=result['error'], code=500)), 500
            
    except Exception as e:
        return jsonify(format_response(message=str(e), code=500)), 500

@problems_bp.route('/analyze-solution', methods=['POST'])
@teacher_required
def analyze_solution():
    """AI分析解答"""
    try:
        data = request.get_json()
        
        problem_description = data.get('problem_description')
        user_code = data.get('user_code')
        language = data.get('language', 'python')
        
        if not problem_description or not user_code:
            return jsonify(format_response(message="题目描述和用户代码不能为空", code=400)), 400
        
        result = problem_generator.analyze_solution(problem_description, user_code, language)
        
        if result['success']:
            return jsonify(format_response(result, "解答分析完成"))
        else:
            return jsonify(format_response(message=result['error'], code=500)), 500
            
    except Exception as e:
        return jsonify(format_response(message=str(e), code=500)), 500

@problems_bp.route('/generate-hints', methods=['POST'])
@teacher_required
def generate_hints():
    """AI生成解题提示"""
    try:
        data = request.get_json()
        
        problem_description = data.get('problem_description')
        user_progress = data.get('user_progress', '')
        
        if not problem_description:
            return jsonify(format_response(message="题目描述不能为空", code=400)), 400
        
        result = problem_generator.generate_hints(problem_description, user_progress)
        
        if result['success']:
            return jsonify(format_response(result, "解题提示生成成功"))
        else:
            return jsonify(format_response(message=result['error'], code=500)), 500
            
    except Exception as e:
        return jsonify(format_response(message=str(e), code=500)), 500

@problems_bp.route('/save-generated', methods=['POST'])
@teacher_required
def save_generated_problem():
    """保存AI生成的题目"""
    try:
        current_user = get_current_user()
        data = request.get_json()
        
        problem_data = data.get('problem')
        if not problem_data:
            return jsonify(format_response(message="题目数据不能为空", code=400)), 400
        
        # 创建新题目
        new_problem = Problem(
            title=problem_data.get('title', 'AI生成题目'),
            description=problem_data.get('description', ''),
            difficulty=problem_data.get('difficulty', 'medium'),
            language=problem_data.get('language', 'python'),
            test_cases=json.dumps(problem_data.get('test_cases', [])),
            answer=problem_data.get('solution', {}).get('code', ''),
            points=10,
            created_by=current_user.id
        )
        
        db.session.add(new_problem)
        db.session.commit()
        
        return jsonify(format_response(new_problem.to_dict(), "AI生成题目保存成功"))
        
    except Exception as e:
        db.session.rollback()
        return jsonify(format_response(message=str(e), code=500)), 500

@problems_bp.route('/stats', methods=['GET'])
@login_required
def get_problem_stats():
    """获取题目统计信息"""
    try:
        # 按难度统计
        difficulty_stats = db.session.query(
            Problem.difficulty, 
            db.func.count(Problem.id)
        ).group_by(Problem.difficulty).all()
        
        # 按语言统计
        language_stats = db.session.query(
            Problem.language, 
            db.func.count(Problem.id)
        ).group_by(Problem.language).all()
        
        # 总题目数
        total_problems = Problem.query.count()
        
        stats = {
            'total': total_problems,
            'difficulty_distribution': dict(difficulty_stats),
            'language_distribution': dict(language_stats)
        }
        
        return jsonify(format_response(stats))
        
    except Exception as e:
        return jsonify(format_response(message=str(e), code=500)), 500
